<?php


namespace app\admin\model\admin;

use app\admin\model\auth\Roles;
use app\admin\model\merchant\MerchantModel;
use app\admin\validate\admin\Admin as val_Admin;

use think\exception\ValidateException;
use think\facade\Session;
use think\Model;
use think\response\Json;
use ulit\CryptAES;

class Admin extends Model
{


    protected $hidden = ['password'];

    protected $autoWriteTimestamp = true;
    protected $json=['channel_ids'];
    protected $jsonAssoc=true;


    /***
     * @inheritDoc ->fetchSql(true)
     * @param $params
     */
    public static function Login($params){
        try {
           validate(val_Admin::class)->scene('login')->check($params);
          $where['username']=$params['username'];


            $aes=new CryptAES();
            $password=$aes->aesEncode($params['password']);
           $where['password']=$password;
           $result=self::where($where)->hidden(['password'])->find();
           if(empty($result)){
               return [
                   'code'=>4002,
                   'msg'=>'账号密码错误',
               ];
           }else{

               if(!empty($result->google) && $result->google !='0'){
                   $res=validate_google_code($result->google,$params['google']);
                   if(!$res){
                       $msg=[
                           'code'=>4003,
                           'msg'=>'谷歌验证码错误',
                       ];
                       return  $msg;
                   }
               }
               $save['loginip']=request()->ip();
               self::where($where)->update($save);

               session('admin_info',$result->toArray());
               $roles=Roles::where(['id'=>$result->role_id])->find();

               $MerchantInfo=MerchantModel::where(['admin_id'=>$result->id])->find();
               $roles && session('role_info',$roles->toArray());
               $MerchantInfo && session('merchant_info',$MerchantInfo->toArray());
               session('role_id',$result->role_id);
               session('admin_id',$result->id);
               session('username',$result['username']);
               $msg=[
                   'code'=>200,
                   'msg'=>'登录成功',
                   'url'=>url('Index/index')->build(),
               ];
               return  $msg;
           }

        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $e->getError();
        }
    }


    /****
     * @param $params
     * @return array|string
     */
    public static function register($params){
        try {
            $result = validate(val_Admin::class)->check($params);
            if (!empty($result)) {

                $add=$params;
                 $aec=new CryptAES();
                $add['password']=$aec->aesEncode($params['password']);
               // unset($add['password_confirm']);
                 self::create($add);
                return [
                    'code'=>200,
                    'msg'=>'添加成功'
                ];

            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $e->getError();
        }
    }

    /****
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminList(){


        $where=[];
           $list= self::where($where)->select();
            $msg=[
                'code'=>200,
                'msg'=>'获取成功',
                'data'=>$list
            ];
        return  $msg;

    }

    /****
     * @param $params
     * @return array|string
     */
    public static function modifyInfo($params){
        try {

                validate(val_Admin::class)->scene('modify')->check($params);
                $save = $params;
                if (!empty($params['password'])) {
                    $aec = new CryptAES();
                    validate(val_Admin::class)->scene('password')->check($params);
                    $save['password'] = $aec->aesEncode($params['password']);
                }else{
                    unset($save['password']);
                }
                unset($save['password_confirm']);

                $result = self::where('id', $params['id'])->update($save);
                if (!empty($result)) {

                    $msg = [
                        'code' => 200,
                        'msg' => '修改成功',
                    ];
                    return $msg;
                } else {
                    $msg = [
                        'code' => 40014,
                        'msg' => '修改失败'
                    ];
                    return $msg;
                }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $e->getError();
        }

    }




    /***
     * @param $token
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function  GetAdminUid($token){

        if(!cache('token_'.$token)){
            $msg=[
                'code'=>401,
                'msg'=>'backend token_已经失效 '
            ];

            echo exit(json_encode($msg));
        };

        $result=self::where('token',$token)->field(['id','token','status'])->find();


        if(empty($result)){
            $msg=[
                'code'=>401,
                'msg'=>'backend token已经失效 '
            ];

            echo exit(json_encode($msg));
        }

        if($result->status==0){
            $msg=[
                'code'=>45000,
                'msg'=>'用户已经禁用'
            ];
            echo exit(json_encode($msg));
        }

        return $result->id;
    }


    public static function logout(){



       return  self::where('id',ADMIN_UID)->save(['token'=>'']);
    }

    /***
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function GetAdminInfo(){

        $result=self::where('id', ADMIN_UID)->hidden(['password','token'])->find();

        return [
            'code' => 200,
            'msg' => '成功',
            'data'=>$result
        ];

    }


    public static function verifyGoogle($google_code){

        $google=self::where('id', ADMIN_UID)->hidden(['password','token'])->value('google');
        if(!empty($google)){
          return  validate_google_code($google,$google_code);
        }else{
            return true;
        }
    }
    

}